//
//  HMPulishViewController.swift
//  HMWeiBo
//
//  Created by Apple on 16/8/6.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class HMPulishViewController: UIViewController,UITextViewDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        // Do any additional setup after loading the view.
        setupNav()
        
        setupText()
        
        setupToolBar()
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolBar:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "insertEmoticon:", name: "emoticon", object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    // 
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "publish")
        
//        title = "发布微博\n换行了吗?"
        
        let titleString = "发布微博\n换行了吗?"
        
        let label = UILabel(frame: CGRectMake(0,0,200,40))
        
        label.font = UIFont.systemFontOfSize(13)
        
        label.textAlignment = .Center
        
        label.numberOfLines = 0
        // NSMutableAttributedString  -- 是一个可变的;可以给赋值之后的 AttributeSting设置颜色,字体,下划线等属性
        // NSAttributedString -- 是不可变的,不可以设置字体
//        let attribute = NSAttributedString(string: titleString)
        
        let attribute = NSMutableAttributedString(string: titleString)
        
        // 添加属性
//        NSFontAttributeName
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(15),NSForegroundColorAttributeName: UIColor.yellowColor(),NSBackgroundColorAttributeName: UIColor.blueColor()], range: NSMakeRange(0, 4))
        
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(14), NSForegroundColorAttributeName: UIColor.orangeColor(),NSUnderlineStyleAttributeName: NSNumber(int: 3)], range: NSMakeRange(4, titleString.characters.count - 4))
        
        
        label.attributedText = attribute
        
        navigationItem.titleView =  label
        
    }
    private func setupText(){
        
        // 加一个label作为一个占位符是可以
        
        view.addSubview(textView)
        
        textView.font = UIFont.systemFontOfSize(16)
        
        textView.holdString = "听说下雨天吃巧克力更配哦~~~"
        
        // 约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view.snp_edges)
        }
        
        textView.delegate = self
        
        
        // 设置textView的滚动消失
        textView.keyboardDismissMode = .OnDrag
        // 只设置 消失还不行,还需要设置textView的滚动方向,让textView垂直
        textView.alwaysBounceVertical = true
        
        
        //MARK:-- 添加图片选择器
        textView.addSubview(chooseView)
        
        chooseView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(textView.snp_centerX)
            make.top.equalTo(textView.snp_top).offset(100)
            
            make.width.equalTo(kUIScreenWidth - 2 * 10)
            make.height.equalTo(kUIScreenWidth - 2 * 10)
            
            
            
        }
        
    }
    private func setupToolBar(){
        
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            
            make.height.equalTo(44)
        }
        
        toolBar.backgroundColor = UIColor.darkGrayColor()
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        // toolBar 添加控件
        var items = [UIBarButtonItem]()
        
        // 循环遍历
        for itemSetting in itemSettings {
            
            
            let imageName = itemSetting["imageName"]
            
            
            
            //
            let button = UIButton(type: UIButtonType.Custom)
            
            button.setImage(UIImage(named: imageName!), forState: UIControlState.Normal)
            
            let highlightedImage = "\(imageName!)_highlighted"
            button.setImage(UIImage(named: highlightedImage), forState: UIControlState.Highlighted)
            /*
                添加视图的时候,什么都没有展示
                1. 有没有添加进来
                2. 有没有frame
                3. 看图层
            */
            
            button.sizeToFit()
            
            // 添加点击事件
            if let action = itemSetting["action"]  {
                // let action: String
                
                // <#T##Selector#>
                //""
                button.addTarget(self , action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            }

            
            // 创建  item
            // 自定义一个button,来实现它的高亮效果
            let item = UIBarButtonItem(customView: button)
            
            // 把item添加到数组里
            items.append(item)
            
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        
        // 遍历完成之后,删除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
    }
    @objc private func dismiss(){
        
        dismissViewControllerAnimated(false) { () -> Void in
            
        }
    }

    @objc private func publish(){
        
//        update() -- 文字
//        upload() -- 图片
        
        // 怎么知道有没有图片
       if chooseView.getImages().count == 0 {
            update()
        } else {
            
            upload()
        }
        
    }
    
    //MARK:-- 发布文本微博
    private func update(){
        
        // 1.
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        // 2.请求参数
        /*
        access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
        status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
        
        连续两次发布的微博不可以重复；
        非会员发表定向微博，分组成员数最多200。
        */
        
        guard let token = HMLoginViewModel.shareInstance.access_token else {
            return
        }
        // 必须做URLencode  -- AFN已经帮我们做了
        let params = ["access_token":token,
                        "status": getPublishString()]
        
        // 3.POST
        HMHTTPClient.request(.POST, URLString: urlString, parameters: params, success: { (jsonDict) -> () in
            
            SVProgressHUD.showErrorWithStatus("发布成功")
            
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus(error.description)
        }
    }
    //MARK:-- 发布图片微博
    private func upload(){
        /*
            图片上传有2种形式
            1. form表单
            2. 把图片二进制,以base64形式转换成NSString,然后以 POST参数的形式传递
        */
        // 1.
         let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"

        
        // 2. 参数
        /*
        access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
        status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
        
        pic	true	binary	要上传的图片，仅支持JPEG、GIF、PNG格式，图片大小小于5M。
        
        请求必须用POST方式提交，并且注意采用multipart/form-data编码方式； -- form表单
        */
        
        guard let access = HMLoginViewModel.shareInstance.access_token else {
            return
        }
        // 注意!!! pic 这个参数并不在 请求的参数里体现
        let params = ["access_token":access,
                    "status": getPublishString(),

        ]
        
        // 3. 
        let afn = AFHTTPSessionManager()
        
        // 获取图片数组 -- 注意: 我们的开发权限只能上传一张图片
        guard  let image = chooseView.getImages().first else {
            return
        }
        
        afn.POST(urlString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
            
            // 在这里组装我们的form表单
            /*
            第一个参数: 二进制文件
            第二个参数: 请求的参数 -- pic
            第三个参数: 文件名 ;文件名随便写
            第四个参数: 告诉服务器我们要上传的文件类型
            */
            // 这个方法是系统提供的 将UIImage转换成NSdata的方法,而且他会进行压缩
            // 第二个参数是压缩系数 -- 这个压缩系数苹果没有详细的告诉你比例大小,我们再和后台进行接口调试的时候,一点一点的试试图片的清晰度就可以了
           let data = UIImageJPEGRepresentation(image, 0.5)
//            for i in 0..<5 {
//                // 5张图片一起上传 会更慢,除非和后台服务器沟通好,否则不要5张图片一起上传
//                formdata.appendPartWithFileData(data!, name: "pic", fileName: "\(i).png", mimeType: "image/jpeg")
//            }
            
             formdata.appendPartWithFileData(data!, name: "pic", fileName: "aa.png", mimeType: "image/jpeg")
            
            }, progress: nil, success: { (_ , JSON) -> Void in
                SVProgressHUD.showErrorWithStatus("成功")
            }) { (_ , error) -> Void in
                SVProgressHUD.showErrorWithStatus("失败")
        }
    }
    
    
    private func getPublishString() -> String{
        
        
        //        printLog(textView.attributedText)
        
        // 对 textView.attributedText 进行遍历
        /*
        第一个参数: attributedText的起始位置和长度
        第二个参数: 默认值 []
        第三个参数: 闭包
        
        
        A[嘻嘻][嘻嘻][嘻嘻]A
        */
        
        // 还有那些闭包是同步的??? -- 对数组进行遍历
        
        
        // 1
        printLog("1")
        var publishString = String()
        textView.attributedText.enumerateAttributesInRange(NSMakeRange(0, textView.attributedText.length), options: []) { (data:[String : AnyObject], range:NSRange, _) -> Void in
            
            // 2
            printLog("2")
            if let attachment = data["NSAttachment"] as? HMTextAttachment{
                
                printLog("表情")
                printLog(attachment.emoticon?.chs)
                // [嘻嘻] -> chs -> HMEmoticon
                // NSTextAttachment
                if let chs = attachment.emoticon?.chs {
                    
                    publishString = publishString + chs
                }
                
            } else {
                
                // 文字
                printLog("文字")
                let subStr = (self.textView.text as NSString).substringWithRange(range)
                
                printLog(subStr)
                publishString = publishString + subStr
                
                
            }
            
        }
        
        // 3
        printLog("3")
        
        return publishString
        
    }
    
    //MARK:-- 懒加载
    private lazy var textView: HMTextView = HMTextView()
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    // 图片选择器
    private lazy var chooseView: HMChooseView = {
    
        let choose = HMChooseView()
        
        weak var weakSelf = self
        
        let chooseClosure = { [weak self] ()->() in
        
//            self.choosePicture()
            self?.choosePicture()
            
//            weakSelf?.choosePicture()
            
        }
        
        choose.closure = chooseClosure
        
        return choose
        
    }()
    
    // chooseView 对闭包有强引用
    // 闭包 对 self 有强引用
    // self 对 chooseView有强引用
    
    private lazy var emoticonView: HMEmoticonView = {
    
        let emoticon = HMEmoticonView()
        
        // 设置frame
        emoticon.frame.size = CGSizeMake(kUIScreenWidth,216)
        
        return emoticon
    }()
    
    deinit{
        
        print("publish 88")
        // 移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

extension HMPulishViewController{

    // 表情是以附件的形式展示在TextView上的,并不是String,所以 textViewDidChange 的调用需要我们手动实现一下
    func textViewDidChange(textView: UITextView) {
        
        // 当有文字的时候,占位符消失
        if textView.hasText() {
            self.textView.holdString = ""
            
        } else {
            
            self.textView.holdString = "听说下雨天吃巧克力更配哦~~~"
        }
        // 一定要注意 重绘 setNeedsDisplay
        self.textView.setNeedsDisplay()
        
    }
    
}

//MARK:-- 底部toolBar的按钮点击事件
extension HMPulishViewController{
    
    @objc private func choosePicture(){
        
        /* UIImagePickerController 类型
        case PhotoLibrary -- 相册
        case Camera -- 相机
        case SavedPhotosAlbum -- 保存图片的相册
        */
        
        // 1. 先检测一下 我们的类型是否可用
//        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
//            
//            // 2. 创建对象
//            let imagePicker = UIImagePickerController()
//            
//            // 3. 设置类型
//            imagePicker.sourceType = .Camera
//            
//            presentViewController(imagePicker, animated: true) { () -> Void in
//                
//            }
//            
//        }
        
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){
            
            // 2. 创建对象
            let imagePicker = UIImagePickerController()
            
            // 3. 设置类型
            imagePicker.sourceType = .SavedPhotosAlbum
            // 4. 代理
            imagePicker.delegate = self
            
            presentViewController(imagePicker, animated: true) { () -> Void in
                
            }
            
        }
        
    }
    
    @objc private func inputEmoticon(){
        
        
        // 点击这里的时候,应该切换到表情键盘
        
        // textView.inputAccessoryView -- 这里是哪里
        
        // textView.inputView -- 这是哪里?
        
      
//        let view = UIView(frame: CGRectMake(0,0,kUIScreenWidth,100))
//        view.backgroundColor = UIColor.redColor()
//        
////        textView.inputAccessoryView = view
        
//        textView.inputView = emoticonView
        
        // textView.inputView = nil 的时候是键盘
        // 有值的时候,是 表情键盘
        
        textView.inputView == nil ? (textView.inputView = emoticonView):(textView.inputView = nil)
        
        // 调用一下这个方法,来实现 inputView的更新
        textView.reloadInputViews()
        
        // 变成第一响应者
        textView.becomeFirstResponder()
    }
}

//MARK:-- 通知方法
extension HMPulishViewController{
    
    @objc private func changeToolBar(noti: NSNotification){
        
        printLog(noti.userInfo)
        /* 键盘出现的时候的通知
        ([
        UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 736}, {414, 271}},
        UIKeyboardCenterEndUserInfoKey: NSPoint: {207, 600.5}, 
        UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {414, 271}},
        UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 465}, {414, 271}}, 
        UIKeyboardAnimationDurationUserInfoKey: 0.25, 
        UIKeyboardCenterBeginUserInfoKey: NSPoint: {207, 871.5},
        UIKeyboardAnimationCurveUserInfoKey: 7, 
        UIKeyboardIsLocalUserInfoKey: 1])

        */
        
        /*
            键盘消失的时候的通知
        
        [UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 736}, {414, 271}},
        UIKeyboardCenterEndUserInfoKey: NSPoint: {207, 871.5}, 
        UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {414, 271}}, 
        UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 736}, {414, 271}},
        UIKeyboardAnimationDurationUserInfoKey: 0.25, 
        UIKeyboardCenterBeginUserInfoKey: NSPoint: {207, 871.5}, 
        UIKeyboardAnimationCurveUserInfoKey: 7, 
        UIKeyboardIsLocalUserInfoKey: 1]
        */
    
        // 把 AnyObject? 的类型转换成 CGRect
        if let endFrame = noti.userInfo?[UIKeyboardFrameEndUserInfoKey]?.CGRectValue {
            
            if endFrame.origin.y == KUIScreenHeight {
                
                // 键盘已经退出
                self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    make.bottom.equalTo(self.view.snp_bottom).offset(0)
                })
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.toolBar.layoutIfNeeded()
                    
                })
                
            } else if endFrame.origin.y == (KUIScreenHeight - endFrame.size.height) {
                self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                    make.bottom.equalTo(self.view.snp_bottom).offset(-endFrame.size.height)
                })
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 键盘出来
                    self.toolBar.layoutIfNeeded()

                   
                })
            }
            
        }

        
        
    }
    
    @objc private func insertEmoticon(noti: NSNotification){
        
        printLog(noti.userInfo)
        
        // 
        if let emoticon = noti.userInfo?["emoticon"] as? HMEmoticon {
            
           
            textView.insertEmoticon(emoticon)
                      
            
        }
        
    }
}

//MARK:-- 系统相册的图片选择的代理
// 这个不是多继承,只是遵守协议
extension HMPulishViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    // 实现代理方法的时候,一定要手动让图片选择器消失
    // 这个方法已经过期了,但是用的还是很多的
    // 因为里边的参数有一个iamge,所以很多人喜欢这个方法,包括我
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        // 应该把图片添加到 choosView的数据源里
//        chooseView.images.removeAll()
        chooseView.addImages(image)
        
        picker.dismissViewControllerAnimated(false) { () -> Void in
            
        }
        
    }
    
//    // 选择完图片之后,走这个方法
//     func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
//        
//        
//        
//        picker.dismissViewControllerAnimated(true) { () -> Void in
//            
//        }
//    }
    
    // 取消选择图片
     func imagePickerControllerDidCancel(picker: UIImagePickerController){
        
        
        picker.dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
}
